import 'dart:convert';

import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/dms_file_odoo_api.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/dms_file.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/loading_dialog.dart';

class SaleInquiryFormFileUpload extends StatefulWidget {
  String? documentno;

  SaleInquiryFormFileUpload({required this.documentno});

  @override
  _SaleInquiryFormFileUploadState createState() => _SaleInquiryFormFileUploadState();
}

class _SaleInquiryFormFileUploadState extends State<SaleInquiryFormFileUpload> {
  late List<DmsFile> dmsFileList = [];

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
  }

  _upload() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowMultiple: true
      allowedExtensions: ['jpg', 'pdf', 'doc'],
    );
    // List<File> files = result!.paths.map((path) => File(path)).toList();
    if (result == null) {
      return;
    }
    // if (result.files.first.size > 1048 * 1048 * 20) {
    //   cryAlert(context, S.of(context).sizeLimit);
    //   return;
    // }
    formKey.currentState!.save();
    setState(() {
      dmsFileList.addAll(result.files.map((file) => DmsFile(name: file.name,content: base64Encode(file.bytes!),directoryId: "634",documentno: widget.documentno)).toList());
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: dmsFileList.map((dmsFile) => CryInput(
          label: '附件名称',
          value: dmsFile.name,
          enable: false,
          onSaved: (v) {
            dmsFile.name = v;
          },
          // validator: (v) {
          //   return v!.isEmpty ? "请上传附件" : null;
          // },
        ),).toList()
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (dmsFileList.length==0) {
              CryUtils.message("请上传附件");
              return;
            }
            List list = dmsFileList.map((dmsFile) => dmsFile.toOdooMap()).toList();
            //打开遮罩
            showDialog(
                context: context,
                builder: (BuildContext context) {
                  return LoadingDialog(
                    title: "上传中...",
                    isCancel: false,
                  );
                });
            // form.save();
            DmsFileOdooApi.upload(list)
                .then((ResponseBodyApi res) {
              //关闭遮罩
              Navigator.pop(context, true);
              if (!res.success!) {
                // CryUtils.message(res.message!);
                return;
              }
              //关闭该窗口
              Navigator.pop(context, true);
              CryUtils.message("上传成功");
            }).onError((error, stackTrace) {
              //关闭遮罩
              Navigator.pop(context, true);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text("附件上传"),
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            form,
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CryButton(
                  label: "上传附件",
                  onPressed: () {
                    _upload();
                  },
                  iconData: Icons.upload_rounded,
                )
              ],
            ),
          ],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}
